package com.mt.system.itemRenderer {
	import com.mt.system.domain.Permission;
	
	import flash.events.MouseEvent;
	
	import mx.controls.CheckBox;
	import mx.controls.Tree;
	import mx.controls.listClasses.IListItemRenderer;
	import mx.controls.treeClasses.TreeItemRenderer;
	import mx.controls.treeClasses.TreeListData;
	import mx.events.ListEvent;
	
	/**      
	 * 类名称：PermissionTreeCheckRenderer<br>
	 * 类描述：<br>
	 * 创建人：马腾<br>
	 * 创建时间：Dec 8, 2012 2:59:53 PM<br>
	 * 修改人：马腾<br>
	 * 修改时间：Dec 8, 2012 2:59:53 PM<br>
	 */
	public class PermissionTreeCheckRenderer extends TreeItemRenderer{
		
		private var _checkBox:CheckBox;
		public var selectedField:String = "selected";
		
		override public function set data(value:Object):void {
			super.data = value;
			_checkBox.selected = data ? data[selectedField] : false;
		}
		
		override protected function createChildren():void {
			super.createChildren();
			_checkBox = new CheckBox();
			addChild(_checkBox);
			_checkBox.addEventListener(MouseEvent.CLICK , clickCheckBox);
			(this.owner as Tree).addEventListener(ListEvent.CHANGE , propertyChange);
		}
		
		protected function propertyChange(event:ListEvent):void {
			this.updateDisplayList(unscaledWidth,unscaledHeight);
		}
		
		protected function clickCheckBox(event:MouseEvent):void {
			if(data && data[selectedField] != undefined ){  
				data[selectedField] = _checkBox.selected;
				setParent(data);
				setChidlren(data);
				(this.owner as Tree).dispatchEvent(new ListEvent(ListEvent.CHANGE));
			}  
		}
		
		private function setParent(data:Object):void {
			if(data.parent && _checkBox.selected){
				data.parent[selectedField] = true;
				setParent(data.parent);
			}
		}
		
		private function setChidlren(data:Object):void {
			if(data.children){
				for each(var obj:Object in data.children){
					obj[selectedField] = _checkBox.selected;
					setChidlren(obj);
				}
			}
		}
		
		override protected function commitProperties():void {
			super.commitProperties();
			_checkBox.selected = data ? data[selectedField] : false;
		}
		
		override protected function measure():void {  
			super.measure();  
			measuredWidth += _checkBox.getExplicitOrMeasuredWidth();  
		}  
		
		override protected function updateDisplayList(unscaledWidth:Number,
													  unscaledHeight:Number):void{
			super.updateDisplayList(unscaledWidth,unscaledHeight);
			var startx:Number = data ? TreeListData( listData ).indent : 0;
			if(disclosureIcon){
				disclosureIcon.x = startx;  
				startx = disclosureIcon.x + disclosureIcon.width;  
			}
			if(icon){
				icon.x = startx;
				startx = icon.x + icon.measuredWidth;
			}
			_checkBox.move(startx + 5 , (unscaledHeight - _checkBox.height) / 2);
			label.x = startx + 5 + _checkBox.getExplicitOrMeasuredWidth();  
			_checkBox.selected = data ? data[selectedField] : false;
			_checkBox.enabled = (this.owner as Tree).enabled;
		}
	}
}